package com.hhxy.handler.security;

import com.alibaba.fastjson.JSON;
import com.hhxy.utils.WebUtils;
import com.hhxy.utils.response.AppHttpCodeEnum;
import com.hhxy.utils.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ghp
 * @date 2023/3/9
 * @title
 * @description 处理未经身份验证的用户试图访问受保护资源的情况
 */
@Slf4j
@Component
public class AuthenticationEntryPointImplHandler implements AuthenticationEntryPoint {

    /**
     * 处理权限认证时的异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        // 用户未登录，直接访问其它需要登录的页面
        log.error("权限认证失败, 异常信息：{}", e.getMessage());
        ResponseResult result = null;
        if (e instanceof BadCredentialsException) {
            // 用户名或密码错误
            result = ResponseResult.errorResult(AppHttpCodeEnum.CLIENT_ACCOUNT_PASSWORD_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        if (e instanceof InsufficientAuthenticationException) {
            // token不存，需要登录
            result = ResponseResult.errorResult(AppHttpCodeEnum.CLIENT_UNLOGIN_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        // 其它错误
        result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_AUTHENTICATION_ERROR);
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
